/**
 * 实现计时器
 * 创建者：Carburn Ashroom
 * 2024.2.29
 */

#include "time_text.h"

namespace Tm {

    QString Time::get_text() const
    {
        if (state == State::not_start)
            return "00:00:00";
        QString tm_str;
        QTextStream t_str {&tm_str};
        int msec {ms%1000};
        int ltm {ms/1000};
        int sec {ltm%60};
        int min {ltm/60};
        t_str.setFieldWidth(2);
        t_str.setPadChar('0');
        t_str << min;
        tm_str += ':';
        t_str << sec;
        tm_str += ':';
        t_str << msec/10;
        return tm_str;
    }

    void Time::start()
    {
        if (state == State::not_start) {
            begin = high_resolution_clock::now();
            state = State::run;
        }
    }

    void Time::set_time()
    {
        if (state != State::run)
            return;
        auto end = high_resolution_clock::now();
        ms = duration_cast<milliseconds>(end-begin).count();
    }

    void Time::operator-=(int msec)
    {
        ms -= msec;
        if (ms < 0)
            throw Negative_error{};
    }

    Time Time::operator-(int msec) const
    {
        Time new_tm {*this};
        new_tm -= msec;
        return new_tm;
    }

    void Time::parse_time(QString str)
    {
        QTextStream t_str {&str};
        QChar ch;
        int min, sec, msec;
        t_str >> min >> ch >> sec >> ch >> msec;
        ms = min*60000+sec*1000+msec*10;
    }

    void Time::parse_time(const QFile& message)
    {
        if (not message.exists())
            return;
        QFile m_file {message.fileName()};
        m_file.open(QIODevice::ReadOnly);
        QTextStream f_str {&m_file};
        parse_time(f_str.readLine());
    }

    bool Time::operator>=(const Time& otm) const
    {
        if (state == State::not_start)
            return false;
        return ms>=otm.ms;
    }

}
